package c.x.jy.common.utils;

import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
 

 

 
/**
 *  
 */
public class QrCodeUtil {
    private static final String format = "jpg";  //二维码格式
    private static final int BLACK = 0xFF000000;//用于设置图案的颜色
    private static final int WHITE = 0xFFFFFFFF; //用于背景色
    private static final int margin = 1;//白边大小
    private static int width = 220;
    private static int height = 220;
    public static void main(String[] s){
         JSONObject jsonObject=new JSONObject();
         jsonObject.put("url","www.baidu.com");
         jsonObject.put("deviceNo","dfda");
         try {
             QrCodeUtil.createQrCode("C:\\Users\\SHLB\\Desktop\\doutu","dede",220,220,jsonObject,"C:\\Users\\SHLB\\Desktop\\doutu\\1.jpg");
         }catch (Exception e){
             e.getStackTrace();
         }
     }
    public static void createQrCode(String filePath, String fileName, Integer width, Integer height, JSONObject json, String logoPath) throws Exception{
        if (StringUtils.isNotEmpty(filePath) && StringUtils.isNotEmpty(filePath)
                && height != null && width != null && json != null) {
            Map<EncodeHintType, Object> map = new HashMap<EncodeHintType, Object>();
            map.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置编码方式
            map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置二维码的纠错级别为最高级别
            map.put(EncodeHintType.MARGIN, margin);//设置二维码白边大小
            String content ="";
            if(json.containsKey("url")){
                content=json.get("url").toString();
            }else{
                content = json.toJSONString();
            }
            try {
                BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,
                        width, height, map);
                if (logoPath == null || logoPath == "") {//生成普通二维码
                    Path path = FileSystems.getDefault().getPath(filePath, fileName);
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    MatrixToImageWriter.writeToPath(bitMatrix, format, path);
                    return;
                }
                //生成带有logo的二维码
                if (logoPath != null && logoPath != "") {
                    File file = new File(filePath);
                    if (!file.exists()) {
                        file.mkdirs();
                    }
                    WriteToPath(bitMatrix, format, new File(filePath + "/" + fileName), logoPath);
                }
            } catch (Exception e) {
                throw new  Exception("生成二维码错误");
            }
        } else {
            throw new  Exception("生成二维码参数错误");
        }

    }

    public static BufferedImage generate(String content, int width, int height, int margin) {
        Map<EncodeHintType, Object> map = new HashMap<EncodeHintType, Object>();
        map.put(EncodeHintType.CHARACTER_SET, "UTF-8");//设置编码方式
        map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);//设置二维码的纠错级别为最高级别
        map.put(EncodeHintType.MARGIN, margin);//设置二维码白边大小

        try {
            BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width, height, map);
            return MatrixToImageWriter.toBufferedImage(bitMatrix);
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return   null;
    }

    private static void WriteToPath(BitMatrix bitMatrix, String format, File file, String logoPath) throws Exception {
        BufferedImage image = toBufferedImage(bitMatrix);
        Graphics2D gs = image.createGraphics();
        Image img = ImageIO.read(new File(logoPath));
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        gs.drawImage(img, (width - 38) / 2, (height - 38) / 2, null);
        gs.dispose();
        img.flush();
        if (!ImageIO.write(image, format, file)) {
            throw new  Exception("不能创建格式为" + format + "的图片");
        }
    }

    private static BufferedImage toBufferedImage(BitMatrix bitMatrix) {
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
    public static void getQrCode(String text,HttpServletResponse response) {
    	getQrCode(text, width, height, margin, response);
	}
    protected static void getQrCode(String text,int w ,int h ,int m ,HttpServletResponse response){
        OutputStream os = null;
        setResponseImg(response);
        try {
        	 BufferedImage img = QrCodeUtil.generate(text.trim(), w, h, m);
             os =  response.getOutputStream();
            ImageIO.write(img, "jpg", os);
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }

    public static void setResponseImg(HttpServletResponse response ){
    	response.setHeader("Pragma","No-cache");
    	response.setHeader("Cache-Control","no-cache");
    	response.setDateHeader("Expires", 0);
    	response.setContentType("image/png");
    }
}
